<template>
  <section>
    <div class="container">
      <div class="container-title">查询条件</div>
      <div class="container-body pd">
        <el-form
          label-position="right"
          label-width="100px"
          :model="searchForm"
          ref="searchForm"
          class="demo-form-inline"
        >
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="主题名称：" size="small" prop="name">
                <el-input
                  v-model="searchForm.name"
                  placeholder="请输入主题名称"
                  prefix-icon="el-icon-search"
                  size="small"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-button
              class="is-tableBtn"
              size="small"
              @click="clearForm('searchForm')"
              >清空</el-button
            >
            <el-button
              class="is-tableBtn"
              type="primary"
              size="small"
              @click="GetThemeList(searchForm)"
              >查询</el-button
            >
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="container">
      <div class="container-title">主题列表</div>
      <div class="container-body pd">
        <el-row>
          <el-button
            type="primary"
            class="btn"
            size="small"
            @click="createNew()"
            >新增主题</el-button
          >
        </el-row>

        <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="name" label="主题名称" align="center">
          </el-table-column>
          <el-table-column
            prop="thumbnailImgUrl"
            label="主题图片"
            align="center"
          >
            <template slot-scope="scope">
              <el-image
                style="width: auto; height: 40px"
                :src="scope.row.thumbnailImgUrl"
                :preview-src-list="[scope.row.thumbnailImgUrl]"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center">
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope">
              <el-button
                class="btnwarning"
                type="warning"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <!-- <el-button
                class="btnwarning"
                type="danger"
                size="mini"
                @click="Delete(scope.$index, scope.row)"
                >删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <div class="pageBox">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            @current-change="currentPage"
          >
          </el-pagination>
          <div class="clear"></div>
        </div>
      </div>
    </div>

    <!-- 新增主题弹窗 -->
    <el-dialog
      :title="editID ? '编辑主题' : '新增主题'"
      :visible.sync="creategoodsClassifyPop"
      width="30%"
      @close="resetFormESC('newThemeForm')"
      center
    >
      <el-form
        :model="newThemeForm"
        :rules="newThemeRule"
        ref="newThemeForm"
        label-width="120px"
        class="demo-newThemeForm"
        size="small"
      >
        <el-form-item label="主题名称" prop="name">
          <el-input
            v-model="newThemeForm.name"
            placeholder="请输入主题名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="缩略图" prop="thumbnailImgUrl">
          <uploadImg
            :showImgUrl="newThemeForm.thumbnailImgUrl"
            @setImg="setImg"
            fiedName="thumbnailImgUrl"
          />
        </el-form-item>
        <el-form-item label="详情图" prop="backgroundImgUrl">
          <uploadImg
            :showImgUrl="newThemeForm.backgroundImgUrl"
            @setImg="setImg"
            fiedName="backgroundImgUrl"
          />
        </el-form-item>
        <el-form-item label="分享图" prop="shareImgUrl">
          <uploadImg
            :showImgUrl="newThemeForm.shareImgUrl"
            @setImg="setImg"
            fiedName="shareImgUrl"
          />
        </el-form-item>
        <el-form-item label="领取页面图" prop="receiveImgUrl">
          <uploadImg
            :showImgUrl="newThemeForm.receiveImgUrl"
            @setImg="setImg"
            fiedName="receiveImgUrl"
          />
        </el-form-item>
        <el-form-item label="祝福语" prop="blessingWords">
          <el-input
            v-model="newThemeForm.blessingWords"
            placeholder="请输入祝福语"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetFormESC('newThemeForm')" size="small"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="
            editID ? updateThemeForm('newThemeForm') : resetForm('newThemeForm')
          "
          size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </section>
</template>
<script>
import uploadImg from "@/components/uploadImg";
export default {
  data() {
    return {
      page: 1,
      total: 0,
      editID: "", // 当前编辑id
      tableData: [],
      loading: true,
      creategoodsClassifyPop: false, // 商品创建弹窗是否展示
      newThemeForm: {
        name: "",
        blessingWords: "",
        thumbnailImgUrl: "",
        backgroundImgUrl: "",
        shareImgUrl: "",
        receiveImgUrl: "",
      },
      newThemeRule: {
        name: [{ required: true, message: "请输入主题名称", trigger: "blur" }],
        blessingWords: [
          { required: true, message: "请输入祝福语", trigger: "blur" },
        ],
      },
      searchForm: {
        id: "",
      },
    };
  },
  created() {
    this.GetThemeList(this.searchForm);
  },
  components: {
    uploadImg,
  },
  methods: {
    clearForm(formName) {
      // 清空筛选
      this.$refs[formName].resetFields();
    },
    setImg(data) {
      this.newThemeForm[data.fiedName] = data.imageUrl;
    },
    createNew() {
      this.creategoodsClassifyPop = true;
      this.newThemeForm = {
        name: "",
      };
    },
    getGoodsImg(data) {
      this.getImg(data.file, "thumbnailImgUrl");
    },
    getGoodsDetailImg(data) {
      this.getImg(data.file, "backgroundImgUrl");
    },
    getImg(file, fileNmae) {
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = async (e) => {
        // file转base64
        let base64 = e.target.result;
        this.newThemeForm[`${fileNmae}`] = base64;
      };
    },
    beforeAvatarUpload(file) {
      console.log(file);
      let reg = /^(\s|\S)+.(png|jpg|gif|jpeg|webp)$/;
      const imgType = reg.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!imgType) {
        this.$message.error("请上传正确图片");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M && imgType;
    },
    onSubmit() {},
    async GetThemeList(searchForm) {
      this.loading = true;
      let skip = (this.page - 1) * 10;
      // 请求案例
      let res = await this.$store.dispatch("GetThemeList", {
        name: searchForm.name,
        skip,
      });
      if (res.success) {
        this.tableData = res.data.itmes || [];
        this.total = res.data.totalCount;
      } else {
        this.$message.error(res.errorMessage || "网络异常");
      }
      this.loading = false;
    },
    async resetForm(formName) {
      // 请求案例
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.editID = "";
          console.log(this[formName]);
          let res = await this.$store.dispatch("PostTheme", {
            name: this[formName].name,
            thumbnailImgUrl: this[formName].thumbnailImgUrl,
            backgroundImgUrl: this[formName].backgroundImgUrl,
            shareImgUrl: this[formName].shareImgUrl,
            receiveImgUrl: this[formName].receiveImgUrl,
            blessingWords: this[formName].blessingWords,
          });
          if (res.success) {
            this.successMsg();
            this.GetThemeList(this.searchForm);
            this.resetFormESC("newThemeForm");
          } else {
            this.$message.error(res.errorMessage || "网络异常");
          }
        } else {
          return false;
        }
      });
    },
    resetFormESC(formName) {
      // 充值表单
      this.creategoodsClassifyPop = false;
      this.$refs[formName].resetFields();
      setTimeout(() => {
        this.editID = "";
      }, 300);
    },
    async handleEdit(index, row) {
      let res = await this.$store.dispatch("GetThemeInfo", {
        id: row.id,
      });
      if (res.success) {
        this.newThemeForm = {
          name: res.data.name,
          backgroundImgUrl: res.data.backgroundImgUrl,
          thumbnailImgUrl: res.data.thumbnailImgUrl,
          shareImgUrl: res.data.shareImgUrl,
          receiveImgUrl: res.data.receiveImgUrl,
          blessingWords: res.data.blessingWords,
        };
        this.editID = row.id;
        this.creategoodsClassifyPop = true;
      } else {
        this.$message.error(res.errorMessage || "网络异常");
      }
    },

    async handleDelete(index, row) {
      let res = await this.$store.dispatch("DeleteTbClassify", {
        id: row.id,
      });
      if (res.success) {
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        this.GetThemeList(this.searchForm);
        this.resetFormESC("newThemeForm");
      } else {
        this.$message.error(res.errorMessage || "网络异常");
      }
    },

    async updateThemeForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 编辑主题
          let res = await this.$store.dispatch("PutTheme", {
            id: this.editID,
            name: this[formName].name,
            thumbnailImgUrl: this[formName].thumbnailImgUrl,
            backgroundImgUrl: this[formName].backgroundImgUrl,
            shareImgUrl: this[formName].shareImgUrl,
            receiveImgUrl: this[formName].receiveImgUrl,
            blessingWords: this[formName].blessingWords,
          });
          if (res.success) {
            this.successMsg();
            this.GetThemeList(this.searchForm);
            this.resetFormESC("newThemeForm");
          } else {
            this.$message.error(res.errorMessage || "网络异常");
          }
          this.editID = "";
        } else {
          return false;
        }
      });
    },

    currentPage(page) {
      this.page = page;
      this.GetThemeList(this.searchForm);
    },

    successMsg() {
      this.$message({
        showClose: true,
        message: "保存成功",
        type: "success",
        duration: 1000,
      });
    },
    Delete(index, row) {
      this.$confirm("此操作将永久删除分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.handleDelete(index, row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/varibles.scss";
.btn {
  margin-bottom: $btnHeight;
  color: $btnwarning;
}
.btnwarning {
  color: $btnwarning;
}
</style>
